package kz.kstu.scantest.business.server.impl;

import kz.kstu.scantest.business.common.exception.KeyAlreadyExists;
import kz.kstu.scantest.business.entity.CommonEntityConstant;
import kz.kstu.scantest.business.entity.Key;
import kz.kstu.scantest.business.entity.guide.Statistic;
import kz.kstu.scantest.business.server.api.AuditService;

import javax.persistence.Query;
import java.util.Date;
import java.util.List;

/**
 * @author Filipp_Stankevich
 *         created 02.09.12 21:46
 */
public class AuditServiceImpl extends AbstractService implements AuditService {
    private static final long STATISTIC_ID = 1L;

    @Override
    public Integer getProcessedFormDataCount() {
        Integer count = getStatistic().getCount();
        return count != null ? count : 0;
    }

    @Override
    public void changeStatistic(Integer count) {
        Statistic statistic = getStatistic();
        statistic.setCount(count);
        save(statistic);
    }

    @Override
    public void saveKey(Key key) throws KeyAlreadyExists {

        Query query = getEntityManager().createNamedQuery(CommonEntityConstant.FIND_KEY_BY_NUMBER);
        query.setParameter("number", key.getNumber());
        List<Key> keys = query.getResultList();

        if (keys.size() > 0) {
            throw new KeyAlreadyExists();
        }

        key.setCreateDate(new Date());

        Integer writeOffCount = key.getWriteOffCount();
        if (writeOffCount != null) {
            int count = getProcessedFormDataCount();
            count -= writeOffCount;
            changeStatistic(count);
        }

        save(key);
    }

    @Override
    public Key findLastKey() {
        Query query = getEntityManager().createNamedQuery(CommonEntityConstant.FIND_LAST_KEY);
        List<Key> keys = query.getResultList();
        if (keys.size() > 0) {
            return keys.get(0);
        } else {
            return null;
        }
    }

    @Override
    public Statistic getStatistic() {
        Statistic statistic = getEntityManager().find(Statistic.class, STATISTIC_ID);
        if (statistic == null) {
            statistic = new Statistic();
            statistic.setId(STATISTIC_ID);
        }
        return statistic;
    }
}
